from pyhive import hive
import pandas as pd
import traceback
import time
import socket


def test_hive_connection(max_retries=3):
    # 打印连接信息
    print("开始测试 Hive 连接...")

    for attempt in range(max_retries):
        try:
            print(f"\n尝试连接 Hive (尝试 {attempt + 1}/{max_retries})...")

            # 替换为你的 CentOS 虚拟机 IP
            host = '192.168.88.161'  # 请替换为你的实际 IP 地址
            print(f"连接到: {host}:10000")

            conn = hive.Connection(
                host=host,
                port=10000,
                database='default',
                username='',  # 如果需要用户名，请添加
                auth='NOSASL',
                configuration={
                    'hive.server2.transport.mode': 'binary',
                    'hive.server2.thrift.sasl.qop': 'auth',
                    'hive.server2.enable.doAs': 'false'
                }
            )

            print("连接成功！")

            print("\n测试查询...")
            cursor = conn.cursor()
            cursor.execute('SHOW DATABASES')
            databases = cursor.fetchall()

            print("\n可用的数据库:")
            for db in databases:
                print(f"- {db[0]}")

            cursor.close()
            conn.close()
            return True

        except Exception as e:
            print(f"\n连接尝试 {attempt + 1} 失败！")
            print(f"错误类型: {type(e).__name__}")
            print(f"错误信息: {str(e)}")
            print("\n详细错误信息:")
            print(traceback.format_exc())

            if attempt < max_retries - 1:
                print(f"\n等待 5 秒后重试...")
                time.sleep(5)
            else:
                print("\n已达到最大重试次数，连接失败。")
                return False


if __name__ == "__main__":
    # 测试网络连接
    host = '192.168.88.161'  # 请替换为你的实际 IP 地址
    print(f"测试与 {host} 的网络连接...")

    try:
        # 测试 ping
        import subprocess

        result = subprocess.run(['ping', '-n', '1', host],
                                capture_output=True,
                                text=True)
        print("Ping 测试结果:")
        print(result.stdout)
    except Exception as e:
        print(f"Ping 测试失败: {str(e)}")

    # 运行 Hive 连接测试
    test_hive_connection() 